package service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.thinkland.juheapi.common.JsonCallBack;
import com.thinkland.juheapi.data.air.AirData;
import com.thinkland.juheapi.data.weather.WeatherData;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import Utils.ShareUtils;
import entity.FutureWeatherBean;
import entity.HoursWeatherBean;
import entity.PMBean;
import entity.Weather;

/**
 * Created by Administrator on 15-11-30.
 */
public class WeatherService extends Service {

    private String city = null;
    private boolean isRunning = false;
    private int count = 0;
    private WeatherServiceBinder binder = new WeatherServiceBinder();


    private List<HoursWeatherBean> list;
    private HoursWeatherBean hoursBean;
    private PMBean pmBean;
    private Weather weather;
    private static final int REPEAT_MSG = 0x01;

    private OnParserCallBack callBack;

    public interface OnParserCallBack {
        public void onParserComplete(List<HoursWeatherBean> list, PMBean pmBean, Weather weather);
    }


    public void setCallBack(OnParserCallBack callBack) {
        this.callBack = callBack;
    }

    public void removeCallBack() {
        callBack = null;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //打开程序默认的城市,从SharePrefence中获取
        city = ShareUtils.getCityName(getApplicationContext());
        handler.sendEmptyMessage(REPEAT_MSG);
    }

    /**
     * Every 30 mins to updata the weather Data
     */

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == REPEAT_MSG) {
                getCityWeather();
                sendEmptyMessageDelayed(REPEAT_MSG, 30 * 60 * 1000);
            }
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();

        Log.i("service", "onDestroy: ");
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("service", "onStartCommand: ");
        return super.onStartCommand(intent, flags, startId);
    }

    public class WeatherServiceBinder extends Binder {
        public WeatherService getService() {

            return WeatherService.this;
        }
    }

    public void getCityWeather() {
        if (isRunning) {
            return;
        }
        isRunning = true;
        count = 0;

        WeatherData weatherData = WeatherData.getInstance();
        weatherData.getByCitys(city, 2, new JsonCallBack() {
            @Override
            public void jsonLoaded(JSONObject jsonObject) {
//                Log.i("WeatherInfo", jsonObject.toString());
//                System.out.printf(jsonObject.toString());

                weather = parserWeather(jsonObject);
                count++;
                if (weather != null) {
//                    setView(weather);
                }

                if (count % 3 == 0 && callBack != null) {
//                    mPullToRefreshScrollView.onRefreshComplete();
                    callBack.onParserComplete(list, pmBean, weather);
                    isRunning = false;
                }
            }
        });

        weatherData.getForecast3h(city, new JsonCallBack() {
            @Override
            public void jsonLoaded(JSONObject jsonObject) {
                list = new ArrayList<HoursWeatherBean>();
                list = parserForecast3h(jsonObject);
                count++;
                if (list != null && list.size() >= 5) {
//                    setHourViews(list);
                }
                if (count % 3 == 0 && callBack != null) {
//                    mPullToRefreshScrollView.onRefreshComplete();
                    callBack.onParserComplete(list, pmBean, weather);
                    isRunning = false;
                }
            }

        });

        AirData airData = AirData.getInstance();
        airData.cityAir(city, new JsonCallBack() {

            @Override
            public void jsonLoaded(JSONObject arg0) {
                pmBean = parserPM(arg0);
                count++;
                if (pmBean != null) {
//                    setPMView(pmBean);
                }
                if (count % 3 == 0 && callBack != null) {
//                    mPullToRefreshScrollView.onRefreshComplete();
                    callBack.onParserComplete(list, pmBean, weather);
                    isRunning = false;
                }
            }
        });
    }

    /**
     * 解析PM
     *
     * @param json
     * @return
     */
    private PMBean parserPM(JSONObject json) {
        PMBean bean = null;
        try {
            int code = json.getInt("resultcode");
            int error_code = json.getInt("error_code");
            if (error_code == 0 && code == 200) {
                bean = new PMBean();
                JSONObject pmJSON = json.getJSONArray("result").getJSONObject(0).getJSONObject("citynow");
                bean.setAqi(pmJSON.getString("AQI"));
                bean.setQuality(pmJSON.getString("quality"));

            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        return bean;

    }


    private Weather parserWeather(JSONObject jsonObject) {
        Weather weather = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");//用于格式化
        int code = 0;
        try {
            code = jsonObject.getInt("resultcode");
            int error_code = jsonObject.getInt("error_code");
            if (error_code == 0 && code == 200) {
                JSONObject resultJson = jsonObject.getJSONObject("result");
                weather = new Weather();

                JSONObject todayJson = resultJson.getJSONObject("today");
                weather.setCity(todayJson.getString("city")); //城市
                weather.setUv_index(todayJson.getString("uv_index"));
                weather.setTemp(todayJson.getString("temperature"));
                weather.setWeather_str(todayJson.getString("weather"));
                weather.setWeather_id(todayJson.getJSONObject("weather_id").getString("fa"));
                weather.setDressing_index(todayJson.getString("dressing_index"));

                JSONObject skJson = resultJson.getJSONObject("sk");
                weather.setWind(skJson.getString("wind_direction") + skJson.getString("wind_strength"));
                weather.setNow_temp(skJson.getString("temp"));
                weather.setRelease(skJson.getString("time"));
                weather.setHumidity(skJson.getString("humidity"));

                // future：未来几天的数据解析
                Date date = new Date(System.currentTimeMillis());
                //获得future
                JSONArray futureArray = resultJson.getJSONArray("future");

                List<FutureWeatherBean> futureList = new ArrayList<FutureWeatherBean>();

                // 因为未来几天不止一天，要进行遍历
                for (int i = 0; i < futureArray.length(); i++) {
                    JSONObject futureJson = futureArray.getJSONObject(i);
                    FutureWeatherBean futureBean = new FutureWeatherBean();
                    Date datef = null;//格式化时间
                    try {
                        datef = sdf.parse(futureJson.getString("date"));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    if (!datef.after(date)) {
                        continue;
                    }
                    futureBean.setTemp(futureJson.getString("temperature"));
                    futureBean.setWeek(futureJson.getString("week"));
                    futureBean.setWeather_id(futureJson.getJSONObject("weather_id").getString("fa"));

                    futureList.add(futureBean); //加入到FutureWeatherBean的list中去

                    if (futureList.size() == 3) {
                        break;
                    }
                }
                weather.setFutureList(futureList);

            } else {
                Toast.makeText(getApplicationContext(), "WEATHER_ERROR",
                        Toast.LENGTH_SHORT).show();
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return weather;
    }

    private List<HoursWeatherBean> parserForecast3h(JSONObject json) {

        List<HoursWeatherBean> list = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
        Date date = new Date(System.currentTimeMillis());

        try {
            int code = json.getInt("resultcode");
            int error_code = json.getInt("error_code");
            if (error_code == 0 && code == 200) {
                list = new ArrayList<HoursWeatherBean>();
                JSONArray resultArray = json.getJSONArray("result");
                for (int i = 0; i < resultArray.length(); i++) {
                    JSONObject hourJson = resultArray.getJSONObject(i);
                    Date hDate = sdf.parse(hourJson.getString("sfdate"));
                    if (!hDate.after(date)) {
                        continue;
                    }
                    HoursWeatherBean bean = new HoursWeatherBean();
                    bean.setWeather_id(hourJson.getString("weatherid"));
                    bean.setTemp(hourJson.getString("temp1"));
                    Calendar c = Calendar.getInstance();
                    c.setTime(hDate);
                    bean.setTime(c.get(Calendar.HOUR_OF_DAY) + "");
                    list.add(bean);
                    if (list.size() == 5) { // 只需要取出5个值就可以
                        break;
                    }
                }

            } else {
                Toast.makeText(getApplicationContext(), "HOURS_ERROR",
                        Toast.LENGTH_SHORT).show();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return list;

    }

    public void getCityWeather(String city) {
        this.city = city;
        ShareUtils.setCityName(getApplicationContext(), city);
        getCityWeather();
    }
}
